import Vue from 'vue'
import Router from 'vue-router'
import Main from '@/components/main'
import parentView from '@/components/parent-view'
import store from '@/store'
import { setToken, getToken, canTurnTo, setTitle } from '@/libs/util'
let routes = [
    {
        path: '/login',
        name: 'login',
        meta: {
            title: 'Login - 登录',
            hideInMenu: true
        },
        component: () => import('@/view/login')
    },
    {
        path: '/',
        name: '_home',
        redirect: '/home',
        component: Main,
        meta: {
            hideInMenu: true,
            notCache: true
        },
        children: [
            {
                path: '/home',
                name: 'home',
                meta: {
                    title: '首页',
                    icon: 'md-home',
                    hideInMenu: true,
                    notCache: true
                },
                component: () => import('@/view/home')
            },{
                path: '/error_404',
                name: 'error_404',
                meta: {
                    hideInMenu: true,
                    notCache: true,
                },
                component: () => import('@/view/home/error_404')
            }
        ]
    }
];
Vue.use(Router);
const router = new Router({
    routes: routes
    // mode: 'history'
});

const turnTo = (to, access, next) => {
    if(/^error404_/.test(to.name)){//路由无权限
        next({ replace: true, name: 'error_404' });
    }else if(canTurnTo(to.name, access, router.options.routes)){
        next();
    } else {
        //未找到路由
        next({ replace: true, name: 'home'});
    }
};
//加载权限路由
const loadMenu = (to, from, next) => {
    store.dispatch('getPermission').then((res) => {
        let routes = [];
        for(let i=0;i<res.data.length;i++){
            let item = res.data[i];
            let r = {};
            r = {
                path: '/'+item.path,
                name: '_'+item.path,
                component: Main,
                meta: {},
                children: []
            };
            if(!item.children){
                r.children.push({
                    path: '/'+item.path,
                    name: item.path,
                    meta: {icon: item.icon, title: item.title, id: item.id},
                    component: () => import('@/view/'+item.path)
                });
            }else{
                r.meta = {icon: item.icon, title: item.title, showAlways: true};
                for(let j=0;j<item.children.length;j++){
                    let childNode = item.children[j];
                    if(!childNode.children){
                        r.children.push({
                            path: '/'+item.path+"_"+childNode.path,
                            name: item.path+"_"+childNode.path,
                            meta: {icon: childNode.icon, title: childNode.title, id: childNode.id},
                            component: () => import('@/view/'+item.path+'/'+childNode.path)
                        });
                    }else{
                        let c = {
                          path: '/'+childNode.path,
                          name: '_'+childNode.path,
                          meta: {},
                          component: parentView,
                          children: []
                        };
                        c.meta = {icon: childNode.icon, title: childNode.title, showAlways: true}
                        for(let x=0;x<childNode.children.length;x++){
                            c.children.push({
                                path: '/'+item.path+"_"+childNode.path+"_"+childNode.children[x].path,
                                name: item.path+"_"+childNode.path+"_"+childNode.children[x].path,
                                meta: {icon: childNode.children[x].icon, title: childNode.children[x].title, id: childNode.children[x].id},
                                component: () => import('@/view/'+item.path+'/'+childNode.path+'/'+childNode.children[x].path)
                            })
                        }
                        r.children.push(c);
                    }
                }
            }
            routes.push(r);
        }
        //console.log(routes)
        router.options.routes = router.options.routes.concat(routes);
        router.addRoutes(routes);
        store.commit('setMenus', router.options.routes);
        store.commit('loadPermission', true);
        next(to.path);
    });
};
//遍历路由
router.beforeEach((to, from, next) => {
    const token = getToken();
    //加载用户权限路由
    if(token && !store.getters.isLoadPermission){
        loadMenu(to, from, next);
        return;
    }
    if (!token && to.name !== 'login') {// 未登录且非登录页
        next({name: 'login'});
    } else if (!token && to.name === 'login') {// 未登陆且登录页
        next();
    } else if (token && to.name === 'login') {// 已登录且登录页
        // 跳转到Home页
        next({name: 'home'});
    } else {
        if (store.state.user.hasGetInfo) {
            turnTo(to, store.state.user.access, next)
        } else {
            store.dispatch('getUserInfo').then(flag => {
                if(flag){
                    turnTo(to, store.state.user.access, next)
                }else{
                    setToken('');
                    next({name: 'login'})
                }
            }).catch(() => {
                setToken('');
                next({name: 'login'})
            });
        }
    }
});

export default router
